package com.alatus.service.impl;

import com.alatus.constant.Constants;
import com.alatus.mapper.TActivityMapper;
import com.alatus.model.TActivity;
import com.alatus.query.ActivityQuery;
import com.alatus.service.ActivityService;
import com.alatus.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {
    @Resource
    private TActivityMapper tActivityMapper;
    @Override
    public PageInfo<TActivity> getActivityByPage(Integer current, ActivityQuery activityQuery) {
//        设置PageHelper和分页情况
        PageHelper.startPage(current, Constants.PAGE_SIZE);
//        查询
        ArrayList<TActivity> list = tActivityMapper.selectActivityByPage(activityQuery);
//        封装分页到PageInfo中
        PageInfo<TActivity> info = new PageInfo<>(list);
        return info;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveActivity(ActivityQuery activityQuery) {
        TActivity tActivity = new TActivity();
//        把query对象的数据复制到activity对象里面
//        这个工具类的复制要求是两个对象的属性名要相同,属性要相同
        BeanUtils.copyProperties(activityQuery,tActivity);
        tActivity.setCreateTime(new Date());
//        通过token解析出的用户获取ID作为创建者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(activityQuery.getToken()).getId();
        tActivity.setCreateBy(loginId);
        return tActivityMapper.insertSelective(tActivity);
    }

    @Override
    public TActivity getActivityById(Integer id) {
        return tActivityMapper.selectDetailByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateActivity(ActivityQuery activityQuery) {
        TActivity tActivity = new TActivity();
        BeanUtils.copyProperties(activityQuery,tActivity);
//        编辑时间
        tActivity.setEditTime(new Date());
//        通过token解析出的用户获取ID作为编辑者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(activityQuery.getToken()).getId();
        tActivity.setEditBy(loginId);
        return tActivityMapper.updateByPrimaryKeySelective(tActivity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteActivtyById(Integer id) {
        return tActivityMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delActivityByIds(List<String> idList) {
        return tActivityMapper.deleteByIds(idList);
    }

    @Override
    public List<TActivity> getOnGoingActivities() {
        return tActivityMapper.selectOnGoingActivities();
    }
}
